package com.veo.controller;

import com.veo.entity.CommonResult;
import com.veo.entity.Payment;
import com.veo.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    //注入eureka的服务发现
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("******插入结果："+result);
        if (result > 0){
            return new CommonResult(200,"插入数据成功，端口："+serverPort,payment);
        }else {
            return new CommonResult(444,"插入数据库失败，端口："+serverPort,null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getById(@PathVariable("id")Long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("******查询结果："+payment);
        if (payment != null){
            return new CommonResult(200,"查询成功，端口："+serverPort,payment);
        }else {
            return new CommonResult(444,"查询失败，没有对应的数据，端口："+serverPort,null);
        }
    }


    @GetMapping("/payment/lb")
    public String getPort(){
        return serverPort;
    }

    @GetMapping("/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for(String service : services){
            log.info("*******element:"+service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for(ServiceInstance info : instances) {
            log.info(info.getServiceId()     +"\t"+info.getHost()+"\t"+info.getPort()+"\t"+info.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("/payment/feign/timeout")
    public String timeout() {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
